package com.edu.bhu.admin.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.edu.bhu.admin.domain.HouApply;
import com.edu.bhu.admin.domain.HouImages;
import com.edu.bhu.admin.domain.HouTag;
import com.edu.bhu.admin.service.*;
import com.edu.bhu.admin.service.impl.HouHouseAndImagesServiceImpl;
import com.edu.bhu.common.config.OverallConfig;
import com.edu.bhu.common.constant.UserConstants;
import com.edu.bhu.common.core.domain.entity.SysRole;
import com.edu.bhu.common.core.domain.entity.SysUser;
import com.edu.bhu.common.utils.ShiroUtils;
import com.edu.bhu.common.utils.StringUtils;
import com.edu.bhu.common.utils.file.FileUploadUtils;
import com.edu.bhu.framework.shiro.util.AuthorizationUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.edu.bhu.common.annotation.Log;
import com.edu.bhu.common.enums.BusinessType;
import com.edu.bhu.admin.domain.HouHouse;
import com.edu.bhu.common.core.controller.BaseController;
import com.edu.bhu.common.core.domain.AjaxResult;
import com.edu.bhu.common.utils.poi.ExcelUtil;
import com.edu.bhu.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 房屋Controller
 * 
 * @author zhangkeyi
 * @date 2022-02-22
 */
@Controller
@RequestMapping("/admin/house")
public class HouHouseController extends BaseController
{
    private String prefix = "admin/house";

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private IHouHouseService houHouseService;

    @Autowired
    private IHouTagService houTagService;

    @Autowired
    private IHouImagesService houImagesService;

    @Autowired
    private IHouHouseAndImagesService houHouseAndImagesService;

    @Autowired
    private IHouApplyService houApplyService;

    @RequiresPermissions("admin:house:view")
    @GetMapping()
    public String house()
    {
        return prefix + "/house";
    }

    /**
     * 进入房源列表页
     */
    @RequiresPermissions("admin:house:view")
    @GetMapping("/houseCard")
    public String houseCard()
    {
        return prefix + "/houseCard";
    }

    /**
     * 查询房屋列表（仅显示自己名下的，admin显示所有）
     */
    @RequiresPermissions("admin:house:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(HouHouse houHouse)
    {
        Long userId = ShiroUtils.getSysUser().getUserId();
        if(userId != 1)//todo 管理员可以看见所有的列表 测试完再改过来
            houHouse.setUserId(userId);
        startPage();
        List<HouHouse> list = houHouseService.selectHouHouseList(houHouse);
        return getDataTable(list);
    }

    /**
     * 查询房屋列表（显示所有 但不包括已出租的和停用的）
     */
    @RequiresPermissions("admin:house:list")
    @PostMapping("/listAll")
    @ResponseBody
    public TableDataInfo listAll(HouHouse houHouse)
    {
        houHouse.getParams().put("listAll","1");
        startPage();
        List<HouHouse> list = houHouseService.selectHouHouseList(houHouse);
        return getDataTable(list);
    }

    /**
     * 查询房屋列表(关联查询)
     */
    @RequiresPermissions("admin:house:list")
    @PostMapping("/listWithDetail")
    @ResponseBody
    public TableDataInfo listWithDetail(HouHouse houHouse)
    {
        startPage();
        List<HouHouse> list = houHouseService.selectHouHouseListWithDetail(houHouse);
        return getDataTable(list);
    }

    /**
     * 导出房屋列表
     */
    @RequiresPermissions("admin:house:export")
    @Log(title = "房屋", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(HouHouse houHouse)
    {
        List<HouHouse> list = houHouseService.selectHouHouseList(houHouse);
        ExcelUtil<HouHouse> util = new ExcelUtil<HouHouse>(HouHouse.class);
        return util.exportExcel(list, "房屋数据");
    }

    /**
     * 新增房屋
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存房屋
     */
    @RequiresPermissions("admin:house:add")
    @Log(title = "房屋", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(HouHouse houHouse)
    {
        return toAjax(houHouseService.insertHouHouse(houHouse));
    }

    /**
     * 修改房屋
     */
    @RequiresPermissions("admin:house:edit")
    @GetMapping("/edit/{houseId}")
    public String edit(@PathVariable("houseId") Long houseId, ModelMap mmap)
    {
        HouHouse houHouse = houHouseService.selectHouHouseByHouseId(houseId);
        mmap.put("houHouse", houHouse);
        return prefix + "/edit";
    }

    /**
     * 修改保存房屋
     */
    @RequiresPermissions("admin:house:edit")
    @Log(title = "房屋", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(HouHouse houHouse)
    {
        return toAjax(houHouseService.updateHouHouse(houHouse));
    }

    /**
     * 房屋状态修改
     */
    @Log(title = "房屋", businessType = BusinessType.UPDATE)
    @RequiresPermissions("admin:house:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(HouHouse houHouse)
    {
        return toAjax(houHouseService.changeStatus(houHouse));
    }

    /**
     * 删除房屋
     */
    @RequiresPermissions("admin:house:remove")
    @Log(title = "房屋", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(houHouseService.deleteHouHouseByHouseIds(ids));
    }

    /**
     * 进入授权标签页
     */
    @GetMapping("/authTag/{houseId}")
    public String authTag(@PathVariable("houseId") Long houseId, ModelMap mmap)
    {
        HouHouse house = houHouseService.selectHouHouseByHouseId(houseId);
        // 获取房屋所属的标签列表
        List<HouTag> tags = houTagService.selectHouTagByHouseId(houseId);
        mmap.put("house", house);
        mmap.put("tags", tags);
        return prefix + "/authTag";
    }

    /**
     * 房屋添加标签
     */
    @RequiresPermissions("admin:house:edit")
    @Log(title = "房屋管理", businessType = BusinessType.GRANT)
    @PostMapping("/authTag/insertAuthTag")
    @ResponseBody
    public AjaxResult insertAuthTag(Long houseId, Long[] tagIds)
    {
        houHouseService.insertHouseAuth(houseId, tagIds);
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return success();
    }

    /**
     * 进入图片选择页
     */
    @GetMapping("/selectImage/{houseId}")
    public String selectImage(@PathVariable("houseId") Long houseId, ModelMap mmap)
    {
        HouHouse house = houHouseService.selectHouHouseByHouseId(houseId);
        //获取房屋所属的图片列表
        List<HouImages> images = houImagesService.selectHouImagesListByHouseId(houseId);
        mmap.put("house", house);
        mmap.put("images", images);
        return prefix + "/selectImage";
    }

    /**
     * 房屋添加图片（多图片上传，同时把图片路径保存到数据库）
     */
    @RequiresPermissions("admin:house:edit")
    @Log(title = "房屋管理", businessType = BusinessType.GRANT)
    @PostMapping("/selectImage/uploads")
    @ResponseBody
    public AjaxResult uploads(List<MultipartFile> files, Long houseId, int imgNum) throws Exception
    {
        int fileNum = files.size();
        if (fileNum + imgNum > 12)
        {
            return error("图片总数不能超过12张！");
        }

        try
        {
            // 上传文件路径
            String filePath = OverallConfig.getUploadPath();
            List<String> fileNames = new ArrayList<>();
            List<String> urls = new ArrayList<>();
            for (MultipartFile file : files)
            {
                HouImages houImages = new HouImages();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                houImages.setImages(fileName);
                houImagesService.insertImagesAndHouseId(houImages, houseId);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除图片
     */
    @RequiresPermissions("admin:house:remove")
    @Log(title = "图片", businessType = BusinessType.DELETE)
    @PostMapping( "/selectImage/removeImg")
    @ResponseBody
    public AjaxResult removeImg(String ids)
    {
        //删除关联信息
        houHouseAndImagesService.deleteHouHouseAndImagesByImageIds(ids);
        return toAjax(houImagesService.deleteHouImagesByImagesIds(ids));
    }

    /**
     * 进入某个房源的详细信息页
     */
    @GetMapping("/houseInfo/{houseId}")
    public String houseInfo(@PathVariable("houseId") Long houseId, ModelMap mmap)
    {
        //拿到房源信息，关联标签信息和用户信息
        HouHouse house = houHouseService.selectHouHouseByHouseIdWithDetail(houseId);
        //获取房屋所属的图片列表
        List<HouImages> images = houImagesService.selectHouImagesListByHouseId(houseId);
        mmap.put("house", house);
        mmap.put("images", images);
        return prefix + "/houseInfo";
    }

    /**
     * 填写租房时长的弹框
     */
    @RequiresPermissions("admin:house:view")
    @GetMapping("/goAddApply/{houseId}")
    public String goAddApply(@PathVariable("houseId") String houseId, ModelMap mmap)
    {
        mmap.put("houseId",houseId);
        return prefix + "/addApply";
    }

    /**
     * 判断是否是自己名下的房屋
     */
    @GetMapping("/ifMyhouse")
    @ResponseBody
    public String ifMyhouse(Long houseId)
    {
        Long userId = ShiroUtils.getSysUser().getUserId();
        HouHouse houHouse = houHouseService.selectHouHouseByHouseId(houseId);
        if(userId.equals(houHouse.getUserId())){
            return "2";//这是我自己的房子
        }
        return "1";//这不是我自己的房子
    }

}
